var map; // map也设置为全局变量
var trainImgArr = [];//存储培训照片全局变量
(function (aH, aN) {
    var pathArr=[]; //轨迹经纬度
    var MapViewPort;//获取地图的视口范围
    var Mcar; //轨迹回放的车
    var TraceData=[];//轨迹原始数据
    var T=0;//播放还是暂停 0 是暂停 1是播放
    var aL=0;//运行到第几个点
    var isSlide = false; //是否在滑动状态
    var selLicNum = ""; //在跑的车的车牌
    trackPlayback = {
        playState:false, //是否在播放状态
        playSpeed:50, //播放速度
        X:0,//拖拉事件第几个点
        init: function () {
            aH(aN).resize(function () {
                var winWidth = aH(aN).width();
                if (winWidth < 1200) {
                    aH("body").css("overflow", "auto");
                } else {
                    aH("body").css("overflow", "hidden");
                }
            });
            aH("body").css("height", aH(aN).height());

            map = new AMap.Map("MapContainer", {
                resizeEnable: true,
                scrollWheel: true,
                zoom: 13
            });
            map.on("zoomend", function () {
                trackPlayback.getViewPort();
            });
            aH(".amap-logo").attr("href", "javascript:void(0)").attr("target", "");
            AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.MapType"], function () {
                map.addControl(new AMap.ToolBar({
                    "direction": false
                }));
                map.addControl(new AMap.Scale());
                map.addControl(new AMap.MapType());
            });
            MarkerMovingControl = function (map, marker, path) {
                this._map = map;
                this._marker = marker;
                this._path = path;
                this._currentIndex = 0;
                marker.setPosition(path[0]);
                marker.setMap(map); //为Marker指定目标显示地图。当参数值取null时，地图上移除当前Marker：setMap(null)

            };
            MarkerMovingControl.prototype.move = function () {
                if (!this._listenToStepend) {
                    this._listenToStepend = AMap.event.addListener(this, "stepend", function () {
                        this.step();
                    }, this);
                }
                this.step();
            };
            MarkerMovingControl.prototype.stop = function () {
                this._marker.stopMove();
            };
            MarkerMovingControl.prototype.restart = function () {
                this._marker.setPosition(this._path[0]);
                var icon;
                if (TraceData[0].CarState.trim() == "熄火") {
                    icon = "../../AMap/vehicleR.png"
                } else if (TraceData[0].CarState.trim() == "行驶") {
                    icon = "../../AMap/vehicleG.png"
                } else if (TraceData[0].CarState.trim() == "停车") {
                    icon = "../../AMap/vehicleY.png"
                } else if (TraceData[0].CarState.trim() == "离线") {
                    icon = "../../AMap/vehicleO.png"
                }

                this._marker.setIcon(icon); //改变车辆图片
                this._currentIndex = 0;
                this.stop();
            };
            MarkerMovingControl.prototype.previous = function () { //上一个点
                if (aL < 2) {
                    this._marker.setPosition(this._path[aL - 1]);
                    this._currentIndex = aL - 1;
                    this.move();
                } else {
                    this._marker.setPosition(this._path[aL - 2]);
                    this._currentIndex = aL - 2;
                    if (T === 1) { //播放状态
                        this.move();
                    } else {
                        if (T === 0) {  //暂停状态
                            this.move();
                            this.stop();
                        }
                    }
                }
            };
            MarkerMovingControl.prototype.next = function () { //直接跳到下一个点
                var pathlen = this._path.length;
                if (aL < pathlen) {
                    this._marker.setPosition(this._path[aL]);
                    this._currentIndex = aL;
                    if (T === 1) {
                        this.move();
                    } else {
                        if (T === 0) {
                            this.move();
                            this.stop();
                        }
                    }
                } else {
                   alert("这已经是最后一个点！");
                }
            };
            MarkerMovingControl.prototype.skip = function () {
                this._marker.setPosition(this._path[trackPlayback.X]);
                this._currentIndex = trackPlayback.X;
                if (T === 1) {
                    this.move();
                } else {
                    if (T === 0) {
                        this.move();
                        this.stop();
                    }
                }
                aL = trackPlayback.X;
            };
            MarkerMovingControl.prototype.step = function () {

                var bc = this._currentIndex + 1; //即将到达的下一个点
                if (bc <= this._path.length) {
                    if (!this._listenToMoveend) {
                        this._listenToMoveend = AMap.event.addListener(this._marker, "moveend", function () {
                            this._currentIndex++; //结束一次 到下一个点

                            AMap.event.trigger(this, "stepend");
                            //事件流程 move (添加监听stepend) step(添加监听moveend) 到事件moving 结束后出发到moveend 然后触发到stepend 再次进入step

                        }, this);
                    }
                    aL = bc; //赋值aL 在第几个点
                 
                    trackPlayback.showInfo();
                    trackPlayback.alterImg();
                    trackPlayback.X++;
                    $("#play_slider").slider("setValue", trackPlayback.X);//滑块运动

                    if (typeof (this._path[bc]) !== "undefined") {
                        if (TraceData[aL].CarState != TraceData[aL - 1].CarState) {
                            var icon;
                            if (TraceData[aL].CarState.trim() == "熄火") {
                                icon = "../../AMap/vehicleR.png"
                            } else if (TraceData[aL].CarState.trim() == "行驶") {
                                icon = "../../AMap/vehicleG.png"
                            } else if (TraceData[aL].CarState.trim() == "停车") {
                                icon = "../../AMap/vehicleY.png"
                            } else if (TraceData[aL].CarState.trim() == "离线") {
                                icon = "../../AMap/vehicleO.png"
                            }

                            this._marker.setIcon(icon); //改变车辆图片
                        }

                        var Xgap = Math.abs(parseFloat(TraceData[aL].LongitudeNew) - parseFloat(TraceData[aL - 1].LongitudeNew));
                        var Ygap = Math.abs(parseFloat(TraceData[aL].LatitudeNew) - parseFloat(TraceData[aL - 1].LatitudeNew));
                        if (Xgap < 0.000095 && Ygap < 0.000095) { //距离太小moveTo 方法不会进入moveend 事件  超过此范围才moveTo
                            this._currentIndex++;
                            if (T === 1&&!isSlide) { //播放状态且没有在滑动
                                setTimeout(function () { //播放状态才回调
                                    this.step();

                                }.bind(this), 120000 / trackPlayback.playSpeed);
                            }
                        } else {
                            this._marker.moveTo(this._path[bc], trackPlayback.playSpeed);


                            AMap.event.addListener(Mcar, "moving", function () { //J 代表车辆
                                var pois = Mcar.getPosition();
                                if (MapViewPort.contains(pois) !== true) {
                                    map.panTo(pois);
                                    trackPlayback.getViewPort();
                                }
                            });
                        }

                    }
                }

            };
        },
        getViewPort:function(){
            var sw = map.getBounds().getSouthWest();
            var ne = map.getBounds().getNorthEast();
            var swlat = sw.lat;
            var swlng = sw.lng;
            var nelat = ne.lat;
            var nelng = ne.lng;
            MapViewPort = new AMap.Bounds([swlng, swlat], [nelng, nelat]);
        },
        trackMap: function () {
            if (pathArr.length > 1) { //ak 就是所有轨迹点
                Mcar = new AMap.Marker({
                    map: map,
                    position: pathArr[0],
                    icon: "../../AMap/vehicle.png",
                    offset: new AMap.Pixel(-26, -13),
                    zIndex: 99999,
                    autoRotation: true,
                    angle: TraceData[0].Direction - 90
                });
                var icon;
                if (TraceData[0].CarState.trim() == "熄火") {
                    icon = "../../AMap/vehicleR.png"
                } else if (TraceData[0].CarState.trim() == "行驶") {
                    icon = "../../AMap/vehicleG.png"
                } else if (TraceData[0].CarState.trim() == "停车") {
                    icon = "../../AMap/vehicleY.png"
                } else if (TraceData[0].CarState.trim() == "离线") {
                    icon = "../../AMap/vehicleO.png"
                }

                Mcar.setIcon(icon); //改变车辆图片

                var be = new AMap.Polyline({
                    map: map,
                    path: pathArr,
                    strokeColor: "#3366ff",
                    strokeOpacity: 0.9,
                    strokeWeight: 2
                    // strokeStyle: "solid",
                    //  showDir: true
                });
                k = new MarkerMovingControl(map, Mcar, pathArr);
                new AMap.Marker({ //开始点
                    map: map,
                    position: pathArr[0],
                    offset: new AMap.Pixel(-20, -32),
                    icon: new AMap.Icon({
                        size: new AMap.Size(40, 40),
                        image: "../../AMap/start.png",
                        imageOffset: new AMap.Pixel(0, 0)
                    })
                });
                new AMap.Marker({ //结束点
                    map: map,
                    position: pathArr[pathArr.length - 1],
                    offset: new AMap.Pixel(-20, -32),
                    icon: new AMap.Icon({
                        size: new AMap.Size(40, 40),
                        image: "../../AMap/end.png",
                        imageOffset: new AMap.Pixel(0, 0)
                    })
                });
                var self = this;
                AMap.event.addListener(Mcar, "click", function () { //为车加上点击事件
                    var content = [];
                    var obj = TraceData[aL - 1];
                    content.push("车牌号码：" + selLicNum);
                    content.push("在线状态：" + obj.CarState);
                    content.push("速度(km/h)：" + obj.Speed);
                    content.push("当前教练：" + obj.CoachName);
                    content.push("当前学员：" + obj.StuName);
                    content.push("定位时间：" + obj.GpsTime);
                    content.push("位置：" + obj.Location);
                    aC = new AMap.InfoWindow({
                        content: content.join("<br/>"),
                        offset: new AMap.Pixel(-1, -1),
                        closeWhenClickMap: true
                    });
                    aC.open(map, Mcar.getPosition());
                });

            }
            map.setFitView();
            trackPlayback.getViewPort();
        },
        reset:function(){ //复位
            pathArr=[]; //轨迹经纬度
            Mcar=null;
            TraceData=[];
            trackPlayback.X = 0;
        },
        query: function (deviceNo, stime, etime, dataType,licNum) {
            var self = this;
            selLicNum = licNum;
            aH.ajax({
                type: "POST",
                url: "/Map/GetHisLocation",
                data: {
                    "deviceNo": deviceNo,
                    "stime": stime,
                    "etime": etime,
                    "dataType": dataType
                },
                dataType: "json",
                async: true,
                beforeSend: function () {
                   // loadMask();
                },
                success: function (hisData) {
                    if (hisData.length > 0) {
                        self.playState = true;

                        trackPlayback.reset();
                        var markers = map.getAllOverlays('marker');
                        var polylines = map.getAllOverlays('polyline');

                        map.remove(markers);
                        map.remove(polylines);//不清除训练场
                        trackPlayback.getHistory(hisData);
                    } else {
                        $.messager.alert("提示", "这段时间无数据！");
                    }
                 
                },
                error: function () {
                    self.playState = false;
                },

            });
            

        },
        getHistory: function (HisData) {
            console.log(HisData)
            TraceData = HisData;
            if (TraceData) {
                var traceLen=TraceData.length;
                for (var bi = 0; bi < traceLen; bi++) {
                    var bM = TraceData[bi];
                    var lng = bM.LongitudeNew;
                    var lat = bM.LatitudeNew;
                    if (lng !== 0 && lat !== 0) {
                        pathArr.push([lng, lat]); //经纬度
                    }
                }
            }
            setTimeout(function () {
                var dataArr = [];
                for (var i = 0; i < TraceData.length; i++) {
                    var d = TraceData[i];
                    dataArr.push({ time: "(" + (i + 1) + ") " + d.GpsTime, status: d.CarState, speed: d.Speed + "km/h" });
                }
                $("#his_grd").datagrid({ data: dataArr });
                $('#his_grd').datagrid({
                    onDblClickCell: function (index, field, value) {
                        I = aH(this).children("td:nth-child(11)").text();
                        Q = aH(this).children("td:nth-child(12)").text();
                        // var b0 = parseInt(aH(this).children("td:nth-child(1)").text());
                        trackPlayback.X = index;
                        k.skip();
                    }
                });

                $("#play_slider").slider({
                    max: TraceData.length,
                    onComplete: function (val) { //slider拖拉事件
                        trackPlayback.X = val;
                        k.skip();
                    },
                    onChange: function (nval, oval) {
                    }
                });

                trackPlayback.trackMap();

            }, 1)
        },
        skipAnimation:function () {
            k.skip();
        },
        stopAnimation: function () {
            trackPlayback.clears();
            k.stop();
            playState = false;
        },
        pauseAnimation:function () { //暂停动画
            T = 0;  //暂停状态
            k.stop();
            var content = [];
            var obj = TraceData[aL - 1];
            content.push("车牌号码：" + selLicNum);
            content.push("在线状态：" + obj.CarState);
            content.push("速度(km/h)：" + obj.Speed);
            content.push("当前教练：" + obj.CoachName);
            content.push("当前学员：" + obj.StuName);
            content.push("定位时间：" + obj.GpsTime);
            content.push("位置：" + obj.Location);
            aC = new AMap.InfoWindow({
                content: content.join("<br/>"),
                offset: new AMap.Pixel(-20, -13),
                closeWhenClickMap: true
            });
            aC.open(map, Mcar.getPosition());
        },
        startAnimation: function () {
            if (this.playState) {
                T = 1; //播放状态
                k.move();
                map.clearInfoWindow();
                map.setZoomAndCenter(18, [TraceData[aL - 1].LongitudeNew, TraceData[aL - 1].LatitudeNew]);
            } else {
                $.messager.alert("提示", "请先查询数据！");
            }

        },
        restartAnimation: function () {
            T = 0;
            k.stop();
            playState = false;
            map.clearInfoWindow();
            if (k !== undefined) {
                k.restart();
            }
            this.X = 0;
            $("#play_slider").slider('reset');
          
        },
        datetime_to_unix:function (datetime){
            var tmp_datetime = datetime.replace(/:/g, '-');
            tmp_datetime = tmp_datetime.replace(/\//g, '-');
            tmp_datetime = tmp_datetime.replace(/ /g,'-');
            var arr = tmp_datetime.split("-");
            var now = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4],arr[5]));
            return parseInt(now.getTime());
        },
        alterImg: function () { //切换轨迹回放的图片
            var len=trainImgArr.length;
            if (len > 0) {
                var obj = TraceData[aL - 1];
                for (var i = 0; i < len; i++) {
                    if (trackPlayback.datetime_to_unix(obj.GpsTime) >= parseInt(trainImgArr[i].PhotoTime.slice(6, trainImgArr[i].PhotoTime.length - 2))) {
                        if ($("#u2>img")[0].src != trainImgArr[i].PhotoUrl) {
                            aH('#u2>img').attr('src', trainImgArr[i].PhotoUrl);
                            aH('#u2>span').html(Common.DateTimeFormatter(trainImgArr[i].PhotoTime));
                        }
                        break;
                    } else if (i + 1 == len) {
                        if ($("#u2>img")[0].src != '/Content/images/no_photo.jpg') {
                            aH('#u2>img').attr('src', '/Content/images/no_photo.jpg');
                            aH('#u2>span').html('');
                        }
                    }  
                }
            }
        },
        showInfo: function () { //实时状态table显示
            var obj = TraceData[aL - 1];
            $("#his_time").text(obj.GpsTime);
            $("#his_speed").text(obj.Speed + "km/h");
            $("#his_direction").text(ChangeDirection(obj.Direction));
            $("#his_lon").text(obj.LongitudeOld);
            $("#his_lat").text(obj.LatitudeOld);


            $("#his_coach").text(obj.CoachName);
            $("#his_student").text(obj.StuName);
            $("#his_status").text(obj.CarState + "|" + obj.PowerState + "|" + obj.GpsState);
            $("#his_alarm").text(obj.Alarm);
            var CameraState = obj.Alarm.indexOf('摄像头故障') == -1 ? '正常' : obj.Alarm;
            $("#his_Camera").text(CameraState);
            $("#his_poi").text(obj.Location);

            aH("#his_grd").datagrid("selectRow", aL-1);
        },
        AddVehicle: function (loc) {
            var self = this;
            var icon;
            if (loc.CarState.trim() == "熄火") {
                icon = "../../AMap/vehicleR.png"
            } else if (loc.CarState.trim() == "行驶") {
                icon = "../../AMap/vehicleG.png"
            } else if (loc.CarState.trim() == "停车") {
                icon = "../../AMap/vehicleY.png"
            } else if (loc.CarState.trim() == "离线") {
                icon = "../../AMap/vehicleO.png"
            }
            var Vehicle = new AMap.Marker({
                map: map,
                position: [parseFloat(loc.LongitudeNew), parseFloat(loc.LatitudeNew)],
                icon: icon,
                offset: new AMap.Pixel(-26, -13),
                zIndex: 99999,
                autoRotation: true,
                angle: loc.Direction - 90, //由于图片是朝右方的  需要减去90度
                extData: loc.DeviceNo
            });


            map.setFitView();
            AMap.event.addListener(Vehicle, "click", function () { //为车加上点击事件
                var bi = [];
                bi.push("车牌号码：" + loc.LicNum);
                bi.push("在线状态：" + loc.CarState);
                bi.push("速度(km/h)：" + loc.Speed);
                bi.push("方向：" + self.changeDirection(loc.Direction));
                bi.push("当前教练：" + loc.CoachName);
                bi.push("当前学员：" + loc.StuName);
                bi.push("定位时间：" + loc.GpsTime);
                bi.push("位置：" + loc.Location);
                content = bi;
                aC = new AMap.InfoWindow({
                    content: content.join("<br/>"),
                    //   offset: new AMap.Pixel(-20, -13),
                    offset: new AMap.Pixel(0, 0),
                    closeWhenClickMap: true
                });
                aC.open(map, Vehicle.getPosition());

            });
        },
        changeDirection: function (angle) { //转换出方向
            if (angle <= 22)
                return "北";
            else if (angle > 22 && angle <= (45 + 22))
                return "东北";
            else if (angle > (45 + 22) && angle <= (90 + 22))
                return "东";
            else if (angle > (90 + 22) && angle <= (90 + 45 + 22))
                return "东南";
            else if (angle > (90 + 45 + 22) && angle <= (180 + 22))
                return "南";
            else if (angle > (180 + 22) && angle <= (180 + 45 + 22))
                return "西南";
            else if (angle > (180 + 45 + 22) && angle <= (270 + 22))
                return "西";
            else if (angle > (270 + 22) && angle <= (270 + 45 + 22))
                return "西北";
            else if (angle > (270 + 45 + 22))
                return "北";
            else if (angle == null)
                return "";
            else
                return "";
        },
        clears: function () {
            aH("#playIcon").attr("class", "resultIcon playIcon");
            aH("#playIcon").removeAttr("data-original-title data-placement data-toggle");
            aH("#playIcon").attr({
                "data-toggle": "tooltip",
                "data-placement": "top",
                "data-original-title": "播放"
            });
           // $("#scroll_Thumb").css("margin-left", 0);
            // $("#scroll_Track").css("width", 0);
            $("#play_slider").slider('reset');
        },
    }

    aH(function () {
        trackPlayback.init();
        //$("#scroll_Thumb").mousedown(function () {
        //    isSlide = true;
        //    k.stop(); //暂停一下播放
        //    $("#playCarListIcon").mousemove(function (a8) {
        //        if (isSlide === false) {
        //            return;
        //        }
        //        a6 = Math.round(a8.clientX) - $("#Demo").offset().left;
        //        if (a6 <= 0) {
        //            a6 = 0;
        //        }
        //        $("#scroll_Thumb").css("margin-left", a6 + "px");
        //        $("#scroll_Track").css("width", a6 + 2 + "px");
        //        if ((a6 + 15) >= $("#scrollBar").width()) {
        //            $("#scroll_Thumb").css("margin-left", $("#scrollBar").width()-10  + "px");
        //            $("#scroll_Track").css("width", $("#scrollBar").width() + 2 + "px");
        //            //  h.value = h.maxValue;
        //        } else {
        //            if (a6 <= 0) {
        //                $("#scroll_Thumb").css("margin-left", "-10px");
        //                $("#scroll_Track").css("width", "2px");
        //            } else {
        //                //  h.value = Math.round(39950 * (a6 / $("#scrollBar").width()));
        //            }
        //        }
        //    });
        //    $(document.body).one('mouseup',function () {
        //        isSlide = false;
        //        trackPlayback.X=Math.round((($("#scroll_Track").width()-2)/$("#scrollBar").width())*(pathArr.length-1));
        //        trackPlayback.skipAnimation();
        //    });
        //});
    })

})($, window);